//! # 中间件集成模块
//!
//! 提供与各种 Web 框架的中间件集成

#[cfg(feature = "axum-integration")]
pub mod axum;

#[cfg(feature = "gateway-integration")]
pub mod gateway;

// 重新导出中间件
#[cfg(feature = "axum-integration")]
pub use axum::{AuthMiddleware, AuthLayer, AuthExtractor};

#[cfg(feature = "gateway-integration")]
pub use gateway::GatewayAuthIntegration;

use rustcloud_security::prelude::*;
use std::sync::Arc;

/// 中间件配置
#[derive(Debug, Clone)]
pub struct MiddlewareConfig {
    /// 跳过认证的路径
    pub skip_paths: Vec<String>,
    /// 可选认证的路径
    pub optional_paths: Vec<String>,
    /// 是否记录审计日志
    pub enable_audit: bool,
    /// 是否启用 CORS
    pub enable_cors: bool,
}

impl Default for MiddlewareConfig {
    fn default() -> Self {
        Self {
            skip_paths: vec![
                "/health".to_string(),
                "/metrics".to_string(),
                "/ready".to_string(),
            ],
            optional_paths: vec![],
            enable_audit: true,
            enable_cors: true,
        }
    }
}

/// 中间件错误类型
#[derive(Debug, thiserror::Error)]
pub enum MiddlewareError {
    #[error("认证失败: {0}")]
    AuthenticationFailed(String),
    
    #[error("授权失败: {0}")]
    AuthorizationFailed(String),
    
    #[error("请求处理失败: {0}")]
    RequestFailed(String),
    
    #[error("配置错误: {0}")]
    ConfigError(String),
}

impl From<SecurityError> for MiddlewareError {
    fn from(err: SecurityError) -> Self {
        match err {
            SecurityError::AuthenticationFailed { reason } => {
                MiddlewareError::AuthenticationFailed(reason)
            },
            SecurityError::AuthorizationFailed { reason } => {
                MiddlewareError::AuthorizationFailed(reason)
            },
            _ => MiddlewareError::RequestFailed(err.to_string()),
        }
    }
}